package com.yyfax.pay.third.facade.fuiou;

import java.util.Iterator;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.yyfax.framework.common.Log;
import com.yyfax.pay.common.annotation.ProtocolType;
import com.yyfax.pay.common.enums.ProtocolEnum;
import com.yyfax.pay.common.exception.PayExceptionCode;


@Service
public class ProtocolAdaptService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @SuppressWarnings("rawtypes")
    private Map<ProtocolEnum, ProtocolService> tradeMap = Maps.newHashMap();

    @Resource
    ApplicationContext context;


    @SuppressWarnings({ "rawtypes", "unchecked" })
    @PostConstruct
    void init() {
        Map<String, ProtocolService> protocolServiceMapMap = context.getBeansOfType(ProtocolService.class);
        Iterator<Map.Entry<String, ProtocolService>> iterator = protocolServiceMapMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, ProtocolService> entry = iterator.next();
            ProtocolType protocolType = AnnotationUtils.findAnnotation(entry.getValue().getClass(), ProtocolType.class);
            if (null != protocolType) {
//                Type[] params;
//                if (AopUtils.isAopProxy(entry.getValue())) {
//                    params = ((ParameterizedType) entry.getValue().getClass().getSuperclass().getGenericSuperclass()).getActualTypeArguments();
//                } else {
//                    params = ((ParameterizedType) entry.getValue().getClass().getGenericSuperclass()).getActualTypeArguments();
//                }
                tradeMap.put(protocolType.value(), entry.getValue());
            }
        }

    }


    public ProtocolService  getAdaptiveTradeService(ProtocolEnum protocolType) {
        final String OP = "ProtocolAdaptService.getAdaptiveTradeService";
        ProtocolService protocolService = tradeMap.get(protocolType);
        if (null == protocolService) {
            logger.error(Log.op(OP).msg("协议类型不支持").kv("tradeMap", tradeMap).kv("protocolType", protocolType)
                    .toString());
            throw PayExceptionCode.SYS_ERROR.exp();
        }
        return protocolService;
    }

}
